# -*- coding: utf-8 -*-

import os
from lib.ucloud.ufile import downloadufile
from src.ucloud.ufile_config import read_config
from multiprocessing.dummy import Pool as ThreadPool
from src.db.query_ucloud_db import read_list
from src.db.ucloud_db import update_path_item
from twisted.internet import reactor
from src.sshconn.ssh_conn import singleton

current_path = os.path.dirname(__file__)
projectPath = os.getcwd()


@singleton
class DownloadLogFile(object):
    def __init__(self):
        self.pool = ThreadPool(100)  # 100是线程池中线程的个数
        public_key, private_key, bucket = read_config()
        self.bucket = bucket
        # 构造下载对象，并设置公私钥
        self.handler = downloadufile.DownloadUFile(public_key, private_key)
        self.index = 0

    def read_log_db(self):
        """
        读取数据库未下载的数据记录
        """
        while True:
            # 读记录
            log_list = read_list({'download_state': 0, 'offset': self.index * 1000, 'count': 1000})
            if log_list is None or len(log_list) <= 0:
                break
            self.index = self.index + 1
            # 线程池
            self.pool.map(self.download_log, log_list)
        print('end')
        reactor.stop()

    def download_log(self, item):
        file_name = item.get("FileName", "")
        if len(file_name) > 0:
            dirs = projectPath + "/logfile/"
            try:
                if not os.path.exists(dirs):
                    os.makedirs(dirs)
            except Exception as e:
                print("download_log makedirs error {0}".format(e))
            save_file = dirs + file_name
            open(save_file, "w+").close()
            # 通过对象类的方法函数请求下载
            ret, resp = self.handler.download_file(self.bucket, file_name, save_file, isprivate=False)
            if resp.status_code == 200:
                # 下载成功
                item['download_state'] = 1
                item['local_file_path'] = save_file
                update_path_item(item)
            else:
                if os.path.exists(save_file):
                    os.remove(save_file)


if __name__ == "__main__":
    reactor.callWhenRunning(DownloadLogFile().read_log_db)
    reactor.run()
